package cn.cdutetc.library.common;

import cn.cdutetc.library.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * CSV工具类
 */
@Slf4j
public class CsvUtils {
    
    /**
     * 生成图书导入模板CSV
     * @param response HTTP响应
     * @param fileName 文件名
     */
    public static void generateBookTemplateCsv(HttpServletResponse response, String fileName) {
        try {
            // 设置响应头
            response.setContentType("text/csv;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String encodedFileName = URLEncoder.encode(fileName + ".csv", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
            
            // 添加BOM以支持Excel正确显示中文
            response.getOutputStream().write(0xEF);
            response.getOutputStream().write(0xBB);
            response.getOutputStream().write(0xBF);
            
            PrintWriter writer = response.getWriter();
            
            // 写入标题行
            writer.println("ISBN号*,图书名称*,作者*,出版社,出版日期(格式:2023-01-01),分类名称*,图书价格,总册数*,图书位置,图书简介");
            
            // 写入示例数据
            writer.println("9787111641247,Java编程思想,Bruce Eckel,机械工业出版社,2023-01-01,计算机科学,108.00,5,科技区A架3层,一本经典的Java编程书籍");
            writer.println("9787302511234,Spring Boot实战,张三,清华大学出版社,2023-06-15,计算机科学,89.00,3,科技区B架2层,Spring Boot开发指南");
            
            writer.flush();
            writer.close();
            
        } catch (IOException e) {
            log.error("生成CSV模板失败", e);
            throw new BizException("生成CSV模板失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成图书信息导出CSV
     * @param response HTTP响应
     * @param fileName 文件名
     * @param bookData 图书数据列表
     */
    public static void generateBookExportCsv(HttpServletResponse response, String fileName, List<Map<String, Object>> bookData) {
        try {
            // 设置响应头
            response.setContentType("text/csv;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String encodedFileName = URLEncoder.encode(fileName + ".csv", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
            
            // 添加BOM以支持Excel正确显示中文
            response.getOutputStream().write(0xEF);
            response.getOutputStream().write(0xBB);
            response.getOutputStream().write(0xBF);
            
            PrintWriter writer = response.getWriter();
            
            // 写入标题行
            writer.println("ISBN号,图书名称,作者,出版社,出版日期,分类名称,图书价格,总册数,在库数量,借出数量,异常数量,图书位置,图书简介");
            
            // 写入数据行
            for (Map<String, Object> book : bookData) {
                StringBuilder line = new StringBuilder();
                line.append(escapeCsvValue(getStringValue(book.get("isbn")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("bookName")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("author")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("publisher")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("publishDate")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("categoryName")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("price")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("totalCopies")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("inStockCount")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("borrowedCount")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("abnormalCount")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("location")))).append(",");
                line.append(escapeCsvValue(getStringValue(book.get("description"))));
                
                writer.println(line.toString());
            }
            
            writer.flush();
            writer.close();
            
        } catch (IOException e) {
            log.error("生成CSV导出失败", e);
            throw new BizException("生成CSV导出失败: " + e.getMessage());
        }
    }
    
    /**
     * 转义CSV值
     */
    private static String escapeCsvValue(String value) {
        if (value == null) {
            return "";
        }
        
        // 如果包含逗号、引号或换行符，需要用引号包围并转义引号
        if (value.contains(",") || value.contains("\"") || value.contains("\n") || value.contains("\r")) {
            return "\"" + value.replace("\"", "\"\"") + "\"";
        }
        
        return value;
    }
    
    /**
     * 安全获取字符串值
     */
    private static String getStringValue(Object value) {
        return value != null ? value.toString() : "";
    }
}
